#!/usr/bin/python3
##new version to add book to database by liuqimin 2018.8.23------
# This script will always think the data at present is better than before, so we use new data to overwrite old data
# Before run this script, use uuid.uuid1() to generate new file name
####
from  book.models import *

from  account.models import *
import os
import re
import xlrd
from souti.settings import *
import sys
import uuid

def get_conf_file(path):
    print('path=', path)
    f=''
    for item in os.listdir(path):
        if '.xls' in item  or  '.xlsx' in item:
            f=item
            break
    return   f

def update_book(path, oss_dir):
    conf_file=get_conf_file(path)
    workbook = xlrd.open_workbook( os.path.join(path, conf_file) )
    sheet = workbook.sheet_by_index(0)

    # -----processing book info------------------
    bookname = sheet.cell(1, 0).value
    bookname_short = sheet.cell(1, 1).value
    author = sheet.cell(1, 2).value
    press = sheet.cell(1, 3).value
    version = sheet.cell(1, 4).value
    cover = sheet.cell(1, 5).value
    ISBN = sheet.cell(1, 6).value.replace('-', '').strip()
    university = sheet.cell(1, 7).value
    university_short = sheet.cell(1, 8).value

    print('bookname=', bookname, 'bookname_short=', bookname_short)

    if not os.path.exists(os.path.join(oss_dir, ISBN)):
        os.makedirs( os.path.join(oss_dir, ISBN) )
#----------always think the new data is better --------
    try:
        cover_img = os.path.join(ISBN, str( uuid.uuid1() ) + os.path.splitext(cover)[-1])
        book = Book.objects.get(ISBN=ISBN)
        os.system('cp "' + os.path.join(path, cover) + '"  ' + os.path.join(oss_dir, cover_img))

        vv=os.path.join(oss_dir, str( book.cover) )
        if os.path.exists(vv):
            os.remove(vv)

        infos = bookname + ' ' + version + ' ' + author + ' ' + university + ' ' + ISBN

        book.name = bookname
        book.shortname = bookname_short
        book.author = author
        book.press = press
        book.version = version
        book.cover = cover_img
        book.ISBN = ISBN
        book.university = university
        book.university_short = university_short
        book.infos = infos
        book.save()

    except:
        kk = os.path.join(oss_dir, ISBN, 'data')
        if not os.path.exists(kk):
            os.makedirs(kk)
        #cover_img = os.path.join(ISBN, uuid.uuid1() + os.path.splitext(cover)[-1])
        #  for oss, copy don't need at present
        os.system('cp "' + os.path.join(path,  cover) + '"  ' + os.path.join(oss_dir, cover_img ))

        infos = bookname + ' ' + version + ' ' + author + ' ' + university + ' ' + ISBN
        book = Book.objects.create(
            name=bookname,
            shortname=bookname_short,
            author=author,
            press=press,
            version=version,
            cover= cover_img,
            ISBN=ISBN,
            university=university,
            university_short=university_short,
            infos=infos,
        )

    # --------processing chapter------------------------
    for i in range(4, sheet.nrows):
        title = sheet.cell(i, 0).value

        index1 = sheet.cell(i, 1).value
        index2 = sheet.cell(i, 2).value
        index3 = sheet.cell(i, 3).value
        ti_count = sheet.cell(i, 4).value
        if title == '':
            break
        print('index1,2,3=', index1,index2,index3)
        if str(index2).strip() == '':
            index1 = int(index1)
            index2 = -1
            index3 = -1
            layers = 1
        elif str(index3).strip() == '':
            index1 = int(index1)
            index2 = int(index2)
            index3 = -1
            layers = 2
        else:
            index1 = int(index1)
            index2 = int(index2)
            index3 = int(index3)
            layers = 3

        if str(ti_count).strip() == '':
            ti_count = -1
        else:
            ti_count = int(ti_count)

        try:
            print('get')
            print('layers=', layers, 'ti_count=', ti_count)
            chapter = Chapter.objects.get(
                book=book,
                index1=index1,
                index2=index2,
                index3=index3,
                title=title,
                # ti_count=ti_count,
                layers=layers,
            )
            chapter.ti_count=ti_count
            chapter.save()
        except:
            print('create')
            print('layers=', layers, 'ti_count=', ti_count, index1, index2, index3)
            chapter = Chapter.objects.create(
                book=book,
                index1=index1,
                index2=index2,
                index3=index3,
                title=title,
                ti_count=ti_count,
                layers=layers,
            )
    return book

def get_book(ISBN):
    try:
        book = Book.objects.get(ISBN=ISBN)
    except:
        book=''
        print('book not found')
        print('ISBN=', ISBN)
        sys.exit(1)
    return book
def get_isbn(conf_file):
    workbook = xlrd.open_workbook( conf_file )
    sheet = workbook.sheet_by_index(0)
    ISBN = sheet.cell(1, 6).value.replace('-', '')
    return ISBN

def update_tis(path,  oss_dir):
    conf_file=get_conf_file(path)
    ISBN=get_isbn(os.path.join(path, conf_file))
    book=get_book(ISBN)

    img_dir=os.path.join(path, 'data')
    for f in os.listdir(img_dir):
        if '_' in f:
            continue
        ch, ti_info = f.split('-')
        ch = ch.split('.')
        ti_info = ti_info.split('.')

        # ti_number=int(ti_info[0])
        ##process chapter
        if len(ch) == 1:
            index1 = int(ch[0])
            index2 = -1
            index3 = -1
        elif len(ch) == 2:
            index1 = int(ch[0])
            index2 = int(ch[1])
            index3 = -1
        elif len(ch) == 3:
            index1 = int(ch[0])
            index2 = int(ch[1])
            index3 = int(ch[2])

        ##process ti info
        if len(ti_info) == 2:
            ti_number = int(ti_info[0])
            xiaoti_number = -1
        elif len(ti_info) == 3:
            ti_number = int(ti_info[0])
            xiaoti_number = int(ti_info[1])

        try:
            print('index1,2,3=', index1, index2, index3)
            chapter = Chapter.objects.get(
                index1=index1,
                index2=index2,
                index3=index3,
                book=book,
            )

        except:
            print('coresponding chapter not found!')
            sys.exit(1)
#----------process ti----------------
        xx = os.path.join(oss_dir, book.ISBN + '/data')
        fname = str( uuid.uuid1() ) + os.path.splitext(f)[-1]
        if not os.path.exists(xx):
            os.makedirs(xx)

        tis = Ti.objects.filter(
            book=book,
            chapter=chapter,
            ti_number=ti_number,
            xiaoti_number=xiaoti_number,
        )
        if tis.count()==0:
            os.system('cp "' + img_dir + '/' + f + '"   ' + os.path.join(xx, fname))
            ti0 = Ti.objects.create(
                book=book,
                chapter=chapter,
                ti_number=ti_number,
                xiaoti_number=xiaoti_number,
                qa=book.ISBN + '/data/' + fname,
            )
            ti0.save()
        else:
            #  for oss, copy don't need at present
            #os.remove( os.path.join( oss_dir, str(ti[0].qa ) ) )
            os.system('cp "' + img_dir + '/' + f + '"   ' + os.path.join(xx, fname))
            i = 0
            for item in tis:
                if i==0:
                    if os.path.exists(os.path.join(oss_dir, str(item.qa))):
                        os.remove(os.path.join(oss_dir, str(item.qa)))
                    item.qa = book.ISBN + '/data/' + fname
                    item.save()
                else:
                    if os.path.exists(os.path.join(oss_dir, str(item.qa))):
                        os.remove(os.path.join(oss_dir, str(item.qa)))
                    item.delete()
                i=i+1
       

#-------------main function start-----------------
conf_dir='/root/souti_data/高等数学-下册-第7版-同济大学数学系'    ##par1   dir contains a lot of books
##----------processing only one book once to detect possible errors---------
oss_path='/tmp/ossfs'
out_dir=os.path.join(oss_path, 'souti/book')
book=update_book(conf_dir, out_dir)

update_tis(conf_dir,  out_dir)
